package org.itstack.demo.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class MyDecoder extends ByteToMessageDecoder {

    private final int BASE_LENGTH = 4;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < BASE_LENGTH) {
            return;
        }

        int beginIndex; // 记录包头位置

        while (true) {
            beginIndex = in.readerIndex();

            // 标记包头开始的index
            in.markReaderIndex();
            // 读到了协议开始的位置，结束while循环
            if (in.readByte() == 0x02) {
                break;
            }
            in.resetReaderIndex();
            in.readByte();
            if (in.readableBytes() < BASE_LENGTH) {
                return;
            }
        }

        int readableCount = in.readableBytes();
        if (readableCount <= 1) {
            in.readerIndex(beginIndex);
            return;
        }

        ByteBuf byteBuf = in.readBytes(1);
        String msgLengthStr = byteBuf.toString(Charset.forName("GBK"));
        int msgLength = Integer.parseInt(msgLengthStr);

        readableCount = in.readableBytes();
        if (readableCount < msgLength + 1) {
            in.readerIndex(beginIndex);
            return;
        }

        ByteBuf msgContent = in.readBytes(msgLength);

        byte end = in.readByte();
        if (end != 0x03) {
            in.readerIndex(beginIndex);
            return;
        }

        out.add(msgContent.toString(Charset.forName("GBK")));

    }
}
